Basics of File Handling in C++

Posted on December 16, 2023 by Vishesh Namdev
Python C C++ Java
C++ Programming

File handling in C++ is a crucial aspect of programming that allows you to read data from and write data to files. C++ provides a set of standard library classes and functions for file handling, which are part of the header. There are three main classes involved in file handling in C++:

1. ofstream (Output File Stream): Used to create and write to files.
2. ifstream (Input File Stream): Used to read from files.
3. fstream (File Stream): Can be used for both reading and writing.

Writing to a File (ofstream):

To write data to a file, you can use the ofstream class. Here's a simple example:

#include <iostream>Copy Code
#include <fstream>

int main() {
// Create an ofstream object and open a file for writing
std::ofstream outFile("example.txt");

// Check if the file is open
if (outFile.is_open()) {
// Write data to the file
outFile << "Hello, File Handling in C++!" << \n;
outFile << 42;

// Close the file
outFile.close();
} else {
std::cerr << "Unable to open the file for writing." << \n;
}

return 0;
}

Reading from a File (ifstream):

To read data from a file, you can use the ifstream class. Here's an example:

#include <iostream>Copy Code
#include <fstream>
#include <string>

int main() {
// Create an ifstream object and open a file for reading
std::ifstream inFile("example.txt");

// Check if the file is open
if (inFile.is_open()) {
// Read data from the file
std::string line;
while (std::getline(inFile, line)) {
std::cout << line << std::endl;
}

// Close the file
inFile.close();
} else {
std::cerr << "Unable to open the file for reading." << std::endl;
}

return 0;
}

Reading and Writing using fstream:

You can use the fstream class to perform both read and write operations on a file.

#include <iostream>Copy Code
#include <fstream>
#include <string>

int main() {
// Create an fstream object and open a file for reading and writing
std::fstream file("example.txt", std::ios::in | std::ios::out | std::ios::app);

// Check if the file is open
if (file.is_open()) {
// Write data to the file
file << "Appending more data.\n";

// Move the file cursor to the beginning
file.seekg(0);

// Read data from the file
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}

// Close the file
file.close();
} else {
std::cerr << "Unable to open the file.\n";
}

return 0;
}

These are just basic examples, and there are many other features and functions available for file handling in C++. Make sure to handle exceptions and errors appropriately, especially when dealing with file I/O operations.